package com.boot.unity.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boot.unity.api.entity.Result;
import com.boot.unity.api.entity.StuSyncDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Slf4j
@Service
@RequiredArgsConstructor
public class OStudentSyncService {
    private final ObjectMapper objectMapper;
    private final RestTemplate restTemplate;
    private static final String appSecret = "123456";
    /****************************推送学时计时数据**************************************/
    /**
     * 进行发送同步多伦的计时系统
     * @param stuSyncDTO
     */
    public void sendDuolun(StuSyncDTO stuSyncDTO){
        // 时间戳
        Long ts = System.currentTimeMillis();
        // hash字符串
        String sign = DigestUtils.sha256Hex(ts + appSecret + stuSyncDTO.getCardnum());
        if (log.isDebugEnabled()) {
            log.debug("sign{}", sign);
        }
        String invokeUrl2 = "https://mainrest.duolunxc.com/services/common/studentInfoSync/" + ts + "/" + sign;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        try {
            HttpEntity httpEntity = new HttpEntity(objectMapper.writeValueAsString(stuSyncDTO), headers);
            ResponseEntity<Result> entity = restTemplate.postForEntity(invokeUrl2, httpEntity, Result.class);
            if (entity.getStatusCode().is2xxSuccessful()){
                Result result = entity.getBody();
                if (result.getErrorcode() != 0) {
                    System.out.println(result.toString());
                }
            }else {
                log.error("调用{}失败,body:{},response:{}", invokeUrl2, JSON.toJSONString(stuSyncDTO), entity);
            }
        }catch (Exception e){
            log.error("调用{}异常,body:{},exception", invokeUrl2, JSON.toJSONString(stuSyncDTO), e.getMessage());
        }
    }



    public void sendZhongHuan(StuSyncDTO stuSyncDTO){
        JSONObject stuJson = (JSONObject) JSONObject.parse(JSON.toJSONString(stuSyncDTO));

        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("strParms",stuJson.toString())
                .build();
        Request request = new Request.Builder()
                .url("http://36.133.121.106:8085/File/AddStudent")
                .method("POST", body)
                .build();
        JSONObject json = null;
        try {
            Response response = client.newCall(request).execute();
            json = (JSONObject) JSONObject.parse(response.body().string());
            System.out.println("中寰推送结果：：：："+json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*******************************停止打学时******************************************/

    public void sendStopZhongHuan(StuSyncDTO stuSyncDTO){
        JSONObject stuJson = (JSONObject) JSONObject.parse(JSON.toJSONString(stuSyncDTO));

        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("strParms",stuJson.toString())
                .build();
        Request request = new Request.Builder()
                .url("http://36.133.121.106:8085/File/AddStudent")
                .method("POST", body)
                .build();
    }


    public void sendStopDuolun(StuSyncDTO stuSyncDTO){
        // 时间戳
        Long ts = System.currentTimeMillis();

        // hash字符串
        String sign = DigestUtils.sha256Hex(ts + appSecret + stuSyncDTO.getCardnum());

        String invokeUrl2 = "https://mainrest.duolunxc.com/services/common/studentInfoSync/" + ts + "/" + sign;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        try {
            HttpEntity httpEntity = new HttpEntity(objectMapper.writeValueAsString(stuSyncDTO), headers);
            ResponseEntity<Result> entity = restTemplate.postForEntity(invokeUrl2, httpEntity, Result.class);

        }catch (Exception e){
            //e.printStackTrace();
            log.error("调用{}异常,body:{},exception", invokeUrl2, JSON.toJSONString(stuSyncDTO), e.getMessage());
        }
    }
    /****************************变更车型***************************************/

    public void sendChangeTrainTypeZh(StuSyncDTO stuSyncDTO){
        JSONObject stuJson = (JSONObject) JSONObject.parse(JSON.toJSONString(stuSyncDTO));

        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("strParms",stuJson.toString())
                .build();
        Request request = new Request.Builder()
                .url("http://36.133.121.106:8085/File/AddStudent")
                .method("POST", body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            JSONObject json = (JSONObject) JSONObject.parse(response.body().string());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendChangeTrainTypeDl(StuSyncDTO stuSyncDTO){
// 时间戳
        Long ts = System.currentTimeMillis();


        // hash字符串
        String sign = DigestUtils.sha256Hex(ts + appSecret + stuSyncDTO.getCardnum());


        String invokeUrl2 = "https://mainrest.duolunxc.com/services/common/studentInfoSync/" + ts + "/" + sign;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        try {
            HttpEntity httpEntity = new HttpEntity(objectMapper.writeValueAsString(stuSyncDTO), headers);
            ResponseEntity<Result> entity = restTemplate.postForEntity(invokeUrl2, httpEntity, Result.class);

        }catch (Exception e){
            //e.printStackTrace();
            log.error("调用{}异常,body:{},exception", invokeUrl2, JSON.toJSONString(stuSyncDTO), e.getMessage());
        }
    }

}
